<template>
  <t-modal
    :title="operateType == 1 ? '新增批注' : '编辑批注'"
    width="900px"
    :visible="visible"
    @cancel="closeModal()"
    @ok="handelOk()"
    wrapClassName="add-annotations-container"
    v-bind="footer"
    forceRender
    v-bind:confirmLoading="submitLoading"
  >
    <a-form-model ref="ruleForm" :model="form" :rules="rules">
      <a-form-model-item label="图纸编号" prop="cadCode">
        <a-input v-model="form.cadCode" placeholder="请输入"></a-input>
      </a-form-model-item>
      <a-row>
        <a-col :span="12">
          <a-form-model-item label="问题名称" prop="issueName">
            <a-input
              v-model="form.issueName"
              placeholder="请输入"
              :title="form.issueName"
            ></a-input>
          </a-form-model-item>
        </a-col>
        <a-col :span="12">
          <a-form-model-item label="问题类型" prop="issueType">
            <a-select
              style="width: 100%"
              placeholder="请选择"
              v-model="form.issueType"
            >
              <a-select-option
                :value="item.dicItemCode"
                v-for="item in issueTypeSoucre"
                :key="item.dicItemCode"
              >
                {{ item.dicItemName }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
      </a-row>

      <a-row>
        <a-col :span="12">
          <a-form-model-item label="问题等级" prop="issueGrade">
            <a-select
              style="width: 100%"
              placeholder="请选择"
              v-model="form.issueGrade"
            >
              <a-select-option
                :value="item.dicItemCode"
                v-for="item in issueGradeSoucre"
                :key="item.dicItemCode"
              >
                {{ item.dicItemName }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :span="12">
          <a-form-model-item label="期望修改时间" prop="solveTime">
            <a-date-picker
              placeholder="请选择"
              style="width: 100%"
              v-model="form.solveTime"
              format="YYYY-MM-DD"
              valueFormat="YYYY-MM-DD"
            />
          </a-form-model-item>
        </a-col>
      </a-row>

      <a-form-model-item label="问题描述" prop="issueDesc">
        <a-input
          type="textarea"
          :rows="4"
          v-model="form.issueDesc"
          placeholder="请输入"
        ></a-input>
      </a-form-model-item>
      <a-form-model-item
        label="图片"
        prop="files"
        :rules="{
          required: true,
          message: '请选择图片',
        }"
      >
        <div class="upload-img">
          <div
            class="upload-button"
            @click="addAnnotationsImg()"
            v-if="operateType == 1"
          >
            <a-icon type="plus" />
            <div class="ant-upload-text">
              上传
            </div>
          </div>
          <div
            class="file-list"
            v-for="(item, index) in form.files"
            :key="index"
          >
            <img :src="item" @click="previewImg(item)" title="点击预览" />
            <!-- 删除按钮 -->
            <div
              class="delete-button"
              @click="deleteImg(item, index)"
              v-if="operateType == 1"
            >
              <a-icon
                type="close"
                :style="{
                  fontSize: '12px',
                  color: '#ffffff',
                }"
              />
            </div>
          </div>
        </div>
      </a-form-model-item>
      <a-form-model-item label="整改人" prop="correctionPeople">
        <a-select
          mode="multiple"
          v-model="form.correctionPeople"
          placeholder="请选择整改人"
        >
          <a-select-option
            :value="item.userNameId"
            v-for="(item, index) in correctionPeopleSoucre"
            :key="index"
          >
            {{ item.userName }}
          </a-select-option>
        </a-select>
      </a-form-model-item>
      <a-form-model-item label="备注">
        <a-input
          type="textarea"
          :rows="4"
          v-model="form.remark"
          placeholder="请输入"
        ></a-input>
      </a-form-model-item>
    </a-form-model>
    <!-- 图片预览弹窗 -->
    <previewImage
      :imgSrc="imgPreview"
      :visible.sync="imgVisible"
    ></previewImage>
  </t-modal>
</template>

<script>
import { axios } from "@/utils/request";
import { PersonnelPopup } from "@/components";
import previewImage from "@/components/TopVUI/custom/previewImage";
import { detailAnnotations } from "@/api/design";
import { getDicItemByCode } from "@/api/common.js";
export default {
  inject: ["fabricCanvas", "drawingModel"],
  components: {
    PersonnelPopup,
    previewImage,
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    reOpen: {
      type: Boolean,
      default: false,
    },
    operateType: {
      type: [String, Number],
      default: "1",
    },
    parameter: {
      type: Object,
      default() {
        return {};
      },
    },
    footer: {
      type: Object,
      default() {
        return {};
      },
    },
    snapshot: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      //问题类型
      issueTypeSoucre: [],
      //问题等级
      issueGradeSoucre: [],
      submitLoading: false,
      //整改人
      correctionPeopleSoucre: [],
      form: {
        uuid: "",
        //最外层数据id
        drawingReviewUuid: "",
        //图纸id
        cadFileUuid: "",
        //图纸编号
        cadCode: "",
        //问题名称
        issueName: "",
        //问题类型
        issueType: undefined,
        //问题等级
        issueGrade: undefined,
        //期望修改时间
        solveTime: "",
        //问题描述
        issueDesc: "",
        //图片
        files: [],
        //备注
        remark: "",
        //整改人
        correctionPeople: [],
      },
      rules: {
        cadCode: [
          {
            required: true,
            message: "请输入图纸编号",
          },
        ],
        issueName: [
          {
            required: true,
            message: "请输入问题名称",
          },
        ],
        issueType: [
          {
            required: true,
            message: "请选择问题类型",
          },
        ],
        issueGrade: [
          {
            required: true,
            message: "请选择问题等级",
          },
        ],
        solveTime: [
          {
            required: true,
            message: "请选择期望修改时间",
          },
        ],
        correctionPeople: [
          {
            required: true,
            message: "请选择整改人",
          },
        ],
      },
      //图片预览弹窗
      imgVisible: false,
      imgPreview: "",
    };
  },

  watch: {
    visible: {
      handler(val) {
        if (val) {
          let { operateType } = this;
          this.form.cadCode = this.parameter.cadCode;
          this.getData();
          //编辑
          if (operateType == 2) {
            this.getDetail();
          } else {
            Promise.all([this.getBimSnapshot(), this.getSnapshot()]).then(
              (result) => {
                this.combineImages(result[0], result[1], (combinedImage) => {
                  if (operateType == 1) {
                    this.form.files.push(combinedImage);
                  }
                });
              }
            );
          }
        }
      },
      immediate: true,
    },
  },

  methods: {
    async getData() {
      //问题类型
      this.issueTypeSoucre = await this.getDicCodeData("issueTypeSJ");
      //问题等级
      this.issueGradeSoucre = await this.getDicCodeData("issueGrade");
      //整改人
      await this.getPeopleData();
    },

    //查询字典表
    getDicCodeData(dicCode = "") {
      return new Promise((resolve, reject) => {
        getDicItemByCode({ code: dicCode })
          .then((res) => {
            let { data } = res;
            resolve(data);
          })
          .catch((_) => {
            reject();
          })
          .finally((_) => {});
      });
    },

    getPeopleData() {
      axios
        .post(
          "/probusiness/drawingReviewComment/getZGUsers",
          {},
          {
            headers: {
              "Content-Type": "application/json",
            },
          }
        )
        .then((res) => {
          this.correctionPeopleSoucre = res?.data ?? [];
        })
        .catch((_) => {
          this.correctionPeopleSoucre = [];
        });
    },

    //详情
    getDetail() {
      let { uuid } = this.parameter;
      detailAnnotations({ uuid })
        .then((res) => {
          let { data } = res;
          this.form = {
            //批注id
            uuid: data.uuid,
            //最外层数据id
            drawingReviewUuid: data.drawingReviewUuid,
            //图纸id
            cadFileUuid: data.cadFileUuid,
            //图纸编号
            cadCode: data.cadCode,
            //问题名称
            issueName: data.issueName,
            //问题类型
            issueType: data?.issueType ?? undefined,
            //问题等级
            issueGrade: data?.issueGrade ?? undefined,
            //期望修改时间
            solveTime: data?.solveTime ?? "",
            //问题描述
            issueDesc: data.issueDesc,
            //图片
            files: data.dealImages,
            //备注
            remark: data.remark,
            //整改人
            major: data?.correctionPeople
              ? data?.correctionPeople.split(",")
              : [],
          };
        })
        .catch((_) => {});
    },

    //新增批注图片
    addAnnotationsImg() {
      this.$emit("update:visible", false);
      this.$emit("update:reOpen", true);
      this.$emit("update:operateType", this.operateType);
    },

    //预览
    previewImg(data) {
      this.imgPreview = data;
      this.imgVisible = true;
    },

    //删除图片
    deleteImg(file, index) {
      this.form.files = this.form.files.filter((v, i) => i != index);
    },

    //监听文件选择
    beforeUpload(file) {
      let filereader = new FileReader();
      filereader.onload = (e) => {
        let src = e.target.result;
        this.form.files.push(src);
      };
      filereader.readAsDataURL(file);
      return false;
    },

    //表单提交
    handelOk() {
      let { operateType } = this;
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.submitLoading = true;
          let { uuid, current } = this.drawingModel();
          let { form } = this;
          let formJson = {
            //最外层数据id
            drawingReviewUuid: uuid,
            //图纸id
            cadFileUuid: current.uuid,
            //图纸编号
            cadCode: form.cadCode,
            //问题名称
            issueName: form.issueName,
            //问题类型
            issueType: form.issueType,
            //问题等级
            issueGrade: form.issueGrade,
            //期望修改时间
            solveTime: form.solveTime,
            //问题描述
            issueDesc: form.issueDesc,
            //图片
            dealImages: form.files,
            //备注
            remark: form.remark,
            //整改人
            fpDealUser: form.correctionPeople.toString(),
          };
          switch (operateType) {
            //编辑
            case 2:
              formJson.uuid = form.uuid;
              break;
            default:
              break;
          }
          axios
            .post(
              "/probusiness/drawingReviewComment/saveOrUpdateData",
              formJson,
              {
                headers: {
                  "Content-Type": "application/json",
                },
              }
            )
            .then((res) => {
              let { statusCode } = res;
              if (statusCode == 200) {
                switch (operateType) {
                  //新增
                  case 1:
                    this.$message.success(`新增成功！`);
                    this.$emit("refresh", { event: "add" });
                    break;
                  //编辑
                  case 2:
                    this.$message.success(`编辑成功！`);
                    this.$emit("refresh", { event: "edit" });
                    break;
                  default:
                    break;
                }
                this.closeModal();
              } else {
                switch (operateType) {
                  //新增
                  case 1:
                    this.$message.error(`新增失败，请稍后重试！`);
                    break;
                  //编辑
                  case 2:
                    this.$message.error(`编辑失败，请稍后重试！`);
                    break;
                  default:
                    break;
                }
              }
            })
            .finally((_) => {
              this.submitLoading = false;
            });
        }
      });
    },

    //重置表单
    resetForm() {
      this.form = {
        uuid: "",
        //最外层数据id
        drawingReviewUuid: "",
        //图纸id
        cadFileUuid: "",
        //图纸编号
        cadCode: "",
        //问题名称
        issueName: "",
        //问题类型
        issueType: undefined,
        //问题等级
        issueGrade: undefined,
        //期望修改时间
        solveTime: "",
        //问题描述
        issueDesc: "",
        //图片
        files: [],
        //备注
        remark: "",
      };
      this.$refs.ruleForm.resetFields();
    },

    //获取bim快照
    getBimSnapshot() {
      return new Promise((resolve, reject) => {
        const canvas = document.getElementById("blackHoleCanvas");
        if (canvas) {
          const context = canvas.getContext("2d");
          const dataUrl = canvas.toDataURL();
          resolve(dataUrl);
        } else {
          resolve("");
        }
      });
    },

    //获取快照
    getSnapshot() {
      return new Promise((resolve, reject) => {
        let canvas = this.fabricCanvas();
        if (canvas) {
          let imageData = canvas.toDataURL({
            format: "png",
            quality: 1,
            enableRetinaScaling: true,
          });
          resolve(imageData);
        } else {
          resolve("");
        }
      });
    },

    //图片合并
    combineImages(image1, image2, callback) {
      // 创建一个canvas元素
      let canvas = document.createElement("canvas");
      let ctx = canvas.getContext("2d");
      // 加载两张图片
      let img1 = new Image();
      img1.src = image1;
      let img2 = new Image();
      img2.src = image2;
      // 确保图片加载完成后再合成
      img1.onload = function() {
        canvas.width = img1.width;
        canvas.height = img1.height;
        ctx.drawImage(img1, 0, 0); // 绘制第一张图片
        ctx.drawImage(img2, 0, 0); // 绘制第二张图片
        // 回调函数返回合成后的图片dataURL
        callback(canvas.toDataURL("image/png"));
      };
    },

    //关闭
    closeModal() {
      this.resetForm();
      this.$emit("update:visible", false);
    },
  },
};
</script>

<style lang="less" scoped>
/deep/.add-annotations-container {
  .upload-img {
    display: flex;
    flex-wrap: wrap;
    .upload-button {
      display: flex;
      width: 110px;
      height: 110px;
      border-radius: 6px;
      background: #fafafa;
      border: 1px dashed #d9d9d9;
      cursor: pointer;
      align-items: center;
      justify-content: center;
      margin-right: 8px;
      flex-direction: column;
      .anticon-plus {
        font-size: 26px;
      }
    }
    .file-list {
      width: 110px;
      height: 110px;
      background: #fafafa;
      border-radius: 6px 6px 6px 6px;
      border: 1px solid #d9d9d9;
      margin: 0 8px 8px 0;
      position: relative;
      img {
        cursor: pointer;
        height: 100%;
        width: 100%;
        object-fit: contain;
      }
      .delete-button {
        position: absolute;
        width: 24px;
        height: 20px;
        background: #ff2d2d;
        border-radius: 0px 6px 0px 20px;
        opacity: 0.6;
        top: 0;
        right: 0;
        cursor: pointer;
        z-index: 99;
        .anticon-close {
          position: relative;
          top: -10px;
          right: -8px;
          font-size: 12px;
          color: #ffffff;
        }
      }
    }
  }
  .ant-form-item {
    display: flex;
    .ant-form-item-label {
      flex-shrink: 0;
      width: 100px;
    }
    .ant-form-item-control-wrapper {
      flex: 1;
      overflow: hidden;
    }
  }
}
</style>
